package com.ifgi.sitcom.campusmapperNDrawer.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.gamificationlibrary.model.leaderboard.Leaderboard;
import com.gamificationlibrary.model.*;
import com.gamificationlibrary.view.LeaderboardView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.PersonBuffer;
import com.ifgi.sitcom.campusmapperNDrawer.R;
import com.ifgi.sitcom.campusmapperNDrawer.adapters.*;
import com.ifgi.sitcom.campusmapperNDrawer.controllers.*;
import com.ifgi.sitcom.campusmapperNDrawer.dialogs.OwnerDialog;
import com.ifgi.sitcom.campusmapperNDrawer.dialogs.SettingsDialog;
import com.ifgi.sitcom.campusmapperNDrawer.fragments.LeaderboardFragment;
import com.ifgi.sitcom.campusmapperNDrawer.fragments.MapFragment;
import com.ifgi.sitcom.campusmapperNDrawer.gamedata.PlayerAdapter;
import com.ifgi.sitcom.campusmapperNDrawer.indoordata.FloorPlan;
import com.ifgi.sitcom.campusmapperNDrawer.io.RDFReader;
import com.ifgi.sitcom.campusmapperNDrawer.outdoordata.Building;


public class MainActivity extends BaseActivity implements OnItemClickListener{

	private DrawerLayout drawlayout=null;
	private ListView listview=null;
	private ActionBarDrawerToggle actbardrawertoggle=null;
	
 
    
	private int[] itemPicture;
	private String[] itemName=null;
	
	private PlayerAdapter pCurrent;
	private ProgressDialog mProgressDialog;
	private LeaderboardFragment fragment;
	private FragmentTransaction ft;
	private String mImageUri;
	private boolean enter;
	private MapFragment dataFragment;
	private MapFragment fragmentmenu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	
		//to manage navigation drawer
		 itemName = new String[] { "Home","Rewards","Leaderboards", "Friends",""};
         itemPicture = new int[] { R.drawable.home,R.drawable.reward,R.drawable.leaderboard,R.drawable.friends,R.drawable.friends};
         
         drawlayout = (DrawerLayout)findViewById(R.id.drawer_layout);
         listview = (ListView) findViewById(R.id.listview_drawer);
         listview.setBackgroundColor(getResources().getColor(R.color.color_drawer));
         listview.setDivider(new ColorDrawable(getResources().getColor(R.color.color_divider)));
         listview.setDividerHeight(1);
         
         getSupportActionBar().removeAllTabs();
         getSupportActionBar().setHomeButtonEnabled(true);
         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
         getSupportActionBar().setDisplayShowHomeEnabled(true);
         getSupportActionBar().setDisplayShowTitleEnabled(true);
         
         drawlayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
         drawlayout.setBackgroundColor(Color.WHITE);
         drawlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
         
        
         CampusMapperApplication.getInstance().setAreas();
         MenuListAdapter menuadapter=new MenuListAdapter(getApplicationContext(), itemName, itemPicture); 
         listview.setAdapter(menuadapter);
         
         actbardrawertoggle= new ActionBarDrawerToggle(this, drawlayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close)
            {
        	 public void onDrawerClosed(View view) {
 				super.onDrawerClosed(view);
 			}

 			public void onDrawerOpened(View drawerView) {
 				super.onDrawerOpened(drawerView);
 			
 			}
        	 
         };
         
         drawlayout.setDrawerListener(actbardrawertoggle);
         listview.setOnItemClickListener(this);
        
         if (savedInstanceState == null)
         {
        	  android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        	// Replace whatever is in the fragment_container view with this fragment,
        	// and add the transaction to the back stack
        	fragmentmenu=  new MapFragment();
        	ft.replace(R.id.content_frame, fragmentmenu,"mapFragment");
        	
        	// Commit the transaction
        	ft.commit();
        
         }
         
        drawlayout.setFocusableInTouchMode(false);
        enter=false;
        Log.v("OnCreateMain","OnCreateMain");
       
	}
	
	
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		actbardrawertoggle.syncState();
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		actbardrawertoggle.onConfigurationChanged(newConfig);
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		selectItem(position);
		
	}
	
	
	 private void selectItem(int position) {
		 
		   //FragmentTransaction transaction = getFragmentManager().beginTransaction();
		  android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
	       
	    
     	    // Locate Position
	        switch (position) {
	        case 0:
	            break;
	        case 1:
	        	MapFragment mapFragment=new MapFragment();
	        	setTitle(R.string.title_activity_main);
	        	for(int i=0;i<getSupportFragmentManager().getBackStackEntryCount();i++){
	        		Log.v("no empty", "no empty");
	        	getSupportFragmentManager().popBackStack();
	        	
	        	}
	        	ft.replace(R.id.content_frame, mapFragment,"mapFragment");
	        	
	            break;
	        case 2:
	        	
	            break;
	        case 3:
	        	LeaderboardController.getInstance().createLeaderboards();
	        	fragment=new LeaderboardFragment();
	            
	            mProgressDialog = ProgressDialog.show(this,
						"Please, wait...",
						"Loading leaderboards",
						true);
				new LeaderboardList().execute(this);
				
	            break;
	       
	        case 4:
	        	
	       
	            break;
	        }
	        ft.commit();
	        listview.setItemChecked(position, true);
	        
	        drawlayout.closeDrawer(listview);
	    }
	 
	 @Override
	public boolean onOptionsItemSelected(MenuItem item) {
	
		 if(item.getItemId()==android.R.id.home)
		 {
			 if(drawlayout.isDrawerOpen(listview))
			 {
				 drawlayout.closeDrawer(listview);
				 if(enter==true)
				 {
					 getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
					 enter=false;
				 }
								 
			 }
			 else {
				drawlayout.openDrawer(listview);
				if(getSupportActionBar().getNavigationMode()==ActionBar.NAVIGATION_MODE_TABS)
				{
				 getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
				 enter=true;
				}
				else
					 enter=false;
			}
		 }
		 switch (item.getItemId()) {
			
			case R.id.action_settings:			
				new SettingsDialog().show(getSupportFragmentManager(), "");
				return true;
			case R.id.action_log_out:			
			
			if (getmPlusClient().isConnected()) {
				getmPlusClient().clearDefaultAccount();
				getmPlusClient().disconnect();
				getmPlusClient().connect();
	                }
				return true;
				
			case R.id.action_revoke_access:			
				
				 if (getmPlusClient().isConnected()) {
					 getmPlusClient().revokeAccessAndDisconnect(this);
				 }
					return true;
			default:
	            return super.onOptionsItemSelected(item);
		 }
	}
	 
	 
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
			getSupportMenuInflater().inflate(R.menu.main, menu);
		      
			return true;
		}

/*
	    @Override
	    public void onConnected(Bundle connectionHint) {
	   
	        Log.v("onConnectedMain","onConnectedMain"); 
	    }
/*
	    @Override
	    public void onDisconnected() {
	        //mSignInStatus.setText(R.string.loading_status);
	        mPlusClient.connect();
	        
	        Log.v("ondiscMain","ondiscMain");
	    }
*/
	   /* @Override
	    public void onConnectionFailed(ConnectionResult result) {
	        mConnectionResult = result;
    		Log.v("onconnectFailed","onconnectFailed");
	    }
	    */

	    private class LeaderboardList extends AsyncTask<Activity, Void, ArrayList<Player>>
		{
			 
			@Override
		        protected ArrayList<Player> doInBackground(Activity... params) {
				
				String s=LeaderboardController.getInstance().queryBuildingsURI(CampusMapperApplication.getInstance().getArea(1));
				String s2=LeaderboardController.getInstance().queryBuildingsURI(CampusMapperApplication.getInstance().getArea(2));
				String[] stotal={s,s2};
				ArrayList<Player> p=LeaderboardController.getInstance().readAllPlayers(stotal);
				 
				return p;
		        }  
		        
		        @Override
		        protected void onPreExecute() {
		        }

		        @Override
		        protected void onProgressUpdate(Void... values) {
		        }
		        
		        @Override
		        protected void onPostExecute(ArrayList<Player> p) {
		        	LeaderboardController.getInstance().populateLeaderboards(p);
					Bundle b = new Bundle();
					ArrayList<Leaderboard> leaderboards=LeaderboardController.getInstance().getLeaderboards();
					Log.v("LSIZE",String.valueOf(leaderboards.size()));
					b.putSerializable(LeaderboardView.EXTRAS_LEADERBOARD, leaderboards);
					
					fragment.setArguments(b);
					
					 android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		        	ft.replace(R.id.content_frame, fragment);
		        	ft.addToBackStack(null);

		        	// Commit the transaction
		        	ft.commitAllowingStateLoss();
					
		        	setTitle(R.string.title_activity_leaderboard);
					mProgressDialog.dismiss();
					
		        }
		}



		


		 @Override
			protected void onSaveInstanceState(Bundle outState) {
			    super.onSaveInstanceState(outState);
			    if (mImageUri != null) {
			        outState.putString("cameraImageUri", mImageUri.toString());
			    }
			}

			@Override
			protected void onRestoreInstanceState(Bundle savedInstanceState) {
			    super.onRestoreInstanceState(savedInstanceState);
			    if (savedInstanceState.containsKey("cameraImageUri")) {
			    	mImageUri = savedInstanceState.getString("cameraImageUri");
//			    	imageUri = Uri.parse(savedInstanceState.getString("cameraImageUri"));
			    }
			}
		
			@Override
			public void onBackPressed()
			{
				if(drawlayout.isDrawerOpen(listview))
				 {
					 drawlayout.closeDrawer(listview);
					 if(enter==true)
					 {
						 getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
						 enter=false;
					 }
				 }
				else
				{
					if(getSupportActionBar().getNavigationMode()==ActionBar.NAVIGATION_MODE_TABS)
					{
						getSupportActionBar().removeAllTabs();
						getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
					}
				super.onBackPressed();
				}
				
			}
			
			   
		    @Override
			public void onConnectionFailed(ConnectionResult result) {
				// TODO Auto-generated method stub
				super.onConnectionFailed(result);
				Intent intent=new Intent(this,SignInActivity.class);
				startActivity(intent);
				finish();
			}
		    
		    public void setmImageUri(String mImageUri) {
				this.mImageUri = mImageUri;
			}


			public String getmImageUri() {
				return mImageUri;
			}
}
